'use strict';

module.exports = function (Product) {
  // 保存前自动更新时间戳
  Product.observe('before save', async ctx => {
    if (ctx.instance) {
      ctx.instance.updatedAt = new Date();
    } else {
      ctx.data.updatedAt = new Date();
    }
  });

  // 示例：自定义远程方法，扣减库存
  Product.sell = async function (id, qty) {
    const product = await Product.findById(id);
    if (!product) throw new Error('Product not found');
    if (product.stock < qty) throw new Error('Insufficient stock');
    product.stock -= qty;
    return product.save();
  };

  Product.remoteMethod('sell', {
    accepts: [
      { arg: 'id', type: 'number', required: true },
      { arg: 'qty', type: 'number', required: true }
    ],
    returns: { arg: 'product', type: 'object', root: true },
    http: { path: '/:id/sell', verb: 'post' }
  });
};
